package validator;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;
import myzzyl.constants.CommonStrField;
import myzzyl.constants.ErrorConstants;
import myzzyl.domain.dto.SysUserDto;
import org.springframework.stereotype.Component;
import validator.annotation.ValidateRegisterRequest;

@Component
@Slf4j
public class RegisterRequestValidator implements ConstraintValidator<ValidateRegisterRequest, SysUserDto> {


    @Override
    public boolean isValid(SysUserDto sysUserDto, ConstraintValidatorContext context) {
        log.info("触发校验:{}", sysUserDto);
        if (StrUtil.isBlank(sysUserDto.getRealName())) {
            setConstraintViolation(context, ErrorConstants.USER_NAME_IS_NULL);
            return false;
        }
        if (StrUtil.isBlank(sysUserDto.getDeptNo()) || StrUtil.isBlank(sysUserDto.getPostNo()) ||
                CollectionUtil.isEmpty(sysUserDto.getRoleVoIds())) {
            setConstraintViolation(context, ErrorConstants.USER_DEPT_OR_POST_ROLE_IS_NULL);
            return false;
        }
        if (!sysUserDto.getMobile().matches(CommonStrField.PHONE_REGEX.getStr())) {
            setConstraintViolation(context, ErrorConstants.USER_PHONE_PATTERN_IS_NOT_CORRECT);
            return false;
        }
        if (!isValidEmail(sysUserDto.getEmail())) {
            setConstraintViolation(context, ErrorConstants.USER_EMAIL_PATTERN_IS_NOT_CORRECT);
            return false;
        }
        return true;
    }


    private boolean isValidEmail(String email) {
        // 判断email是否有@并且只有一个
        int index = email.indexOf("@");
        if (index == - 1 || email.indexOf("@", index + 1) != -1) {
            return false;
        }

        // 判断email的@是否在开头和结尾
        if (index == 0 || index == email.length() - 1) {
            return false;
        }

        // 判断email的@前后是否有.
        return email.charAt(index - 1) != '.' && email.charAt(index + 1) != '.';
    }


    private void setConstraintViolation(ConstraintValidatorContext context, ErrorConstants errorConstants) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(errorConstants.getMessage()).addConstraintViolation();
    }


}
